<template>
    <div class="purchase-order-container">
        <!-- 搜索栏 -->
        <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
            <el-input v-model="searchParams.orderNo" style="width: 240px; padding-right: 15px;" placeholder="请输入订单编号" />
            <el-input v-model="searchParams.supplierName" style="width: 240px;" placeholder="请输入供应商名称" />
<!--            <el-date-picker v-model="searchParams.startDate" type="date" placeholder="起始日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="margin-right: 10px;margin-left: 10px; width: 150px;" />-->
<!--            <el-date-picker v-model="searchParams.endDate" type="date" placeholder="结束日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="width: 150px;" />-->
            <el-icon @click="getPurchaseList()" style="margin-left: 20px; height: 25px; width: 25px;">
                <Search />
            </el-icon>
            <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
                <Refresh />
            </el-icon>
            <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">创建采购订单</el-button>
        </div>

        <!-- 采购订单表格 -->
        <el-table :data="purchaseList" style="width: 100%" stripe border="true">
            <el-table-column label="序号" width="80px" #default="scope" align="center">
                {{ scope.$index + 1 }}
            </el-table-column>
            <el-table-column prop="id" label="订单ID" width="180" align="center" />
            <el-table-column prop="orderNo" label="订单编号" width="180" align="center" />
            <el-table-column prop="supplierName" label="供应商名称" width="180" align="center" />
            <el-table-column prop="orderDate" label="订单日期" width="180" align="center" />
            <el-table-column prop="status" label="订单状态" width="120" #default="scope" align="center">
                <span v-if="scope.row.status == 0" style="color: gray;">待审核</span>
                <span v-if="scope.row.status == 1" style="color: green;">已审核</span>
                <span v-if="scope.row.status == 2" style="color: blue;">已付款</span>
                <span v-if="scope.row.status == 3" style="color: red;">已取消</span>
            </el-table-column>
            <el-table-column label="操作" width="250px" fixed="right" align="center" #default="scope">
                <el-button type="primary" plain @click="viewPurchaseDetails(scope.row.id)">详情</el-button>
                <el-button type="warning" plain @click="showEditDialog(scope.row)">修改</el-button>
                <el-button type="danger" plain @click="deletePurchaseOrder(scope.row.id)">删除</el-button>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
            <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
                :page-sizes="[3, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 创建/编辑采购订单对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑采购订单' : '创建采购订单'" width="900px"
            :before-close="handleDialogClose" :close-on-click-modal="false">
            <el-form :model="purchaseOrder" label-width="120px" style="padding: 15px 0;" :rules="formRules" ref="purchaseForm">
                <el-form-item label="订单编号" prop="orderNo" v-if="isEdit">
                    <el-input v-model="purchaseOrder.orderNo" disabled placeholder="系统自动生成" />
                </el-form-item>
                <el-form-item label="供应商名称" prop="supplierId">
                    <el-select v-model="purchaseOrder.supplierId" placeholder="请选择供应商" clearable>
                        <el-option v-for="supplier in suppliers" :key="supplier.id" :label="supplier.name" :value="supplier.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="订单日期" prop="orderDate">
                    <el-date-picker v-model="purchaseOrder.orderDate" type="date" placeholder="请选择订单日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="订单状态" prop="status" v-if="isEdit">
                    <el-select v-model="purchaseOrder.status" placeholder="请选择订单状态">
                        <el-option label="待审核" :value="0" />
                        <el-option label="已审核" :value="1" />
                        <el-option label="已付款" :value="2" />
                        <el-option label="已取消" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="purchaseOrder.remark" type="textarea" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>
            <!-- 新增：采购商品明细表格 -->
            <div style="margin: 10px 0 0 0;">
                <h4>采购商品明细</h4>
                <el-table :data="purchaseOrder.items || []" style="width: 100%; margin-bottom: 10px;">
                    <el-table-column label="序号" width="60" #default="scope" align="center">
                        {{ scope.$index + 1 }}
                    </el-table-column>
                    <el-table-column label="产品" width="200" #default="scope" align="center">
                        <el-select v-model="scope.row.productId" placeholder="请选择产品" filterable style="width: 160px" @change="val => handleProductChange(scope.row, val)">
                            <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.id" />
                        </el-select>
                    </el-table-column>
                    <el-table-column label="数量" width="170" #default="scope" align="center">
                        <el-input-number v-model="scope.row.quantity" :min="1" :max="999999" :step="1" :precision="0" controls-position="default" style="width: 120px" @change="val => calcAmount(scope.row)" />
                    </el-table-column>
                    <el-table-column label="单价" width="170" #default="scope" align="center">
                        <el-input-number v-model="scope.row.unitPrice" :min="0" :max="999999" :step="1" :precision="0" controls-position="default" style="width: 120px" @change="val => calcAmount(scope.row)" />
                    </el-table-column>
                    <el-table-column label="金额" width="120" #default="scope" align="center">
                        <span>{{ scope.row.amount || 0 }}</span>
                    </el-table-column>
                    <el-table-column label="操作" width="80" #default="scope" align="center">
                        <el-button type="danger" size="small" @click="removeItem(scope.$index)">删除</el-button>
                    </el-table-column>
                </el-table>
                <el-button type="primary" size="small" @click="addItem">添加商品</el-button>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose" size="default">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="default">确认{{ isEdit ? '修改' : '创建' }}</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 采购订单详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="采购订单详情" width="900px" :before-close="handleDetailDialogClose" :close-on-click-modal="false">
            <div v-if="currentPurchaseOrder" class="purchase-detail">
                <div class="detail-header">
                    <p><span class="label">订单编号：</span>{{ currentPurchaseOrder.orderNo }}</p>
                    <p><span class="label">供应商名称：</span>{{ currentPurchaseOrder.supplierName }}</p>
                    <p><span class="label">订单日期：</span>{{ currentPurchaseOrder.orderDate }}</p>
                    <p><span class="label">订单状态：</span>
                        <span v-if="currentPurchaseOrder.status == 0" style="color: gray;">待审核</span>
                        <span v-if="currentPurchaseOrder.status == 1" style="color: green;">已审核</span>
                        <span v-if="currentPurchaseOrder.status == 2" style="color: blue;">已付款</span>
                        <span v-if="currentPurchaseOrder.status == 3" style="color: red;">已取消</span>
                    </p>
                    <p><span class="label">备注：</span>{{ currentPurchaseOrder.remark }}</p>
                </div>

                <div class="detail-items">
                    <h3>采购订单明细</h3>
                    <el-table :data="currentPurchaseOrder.items" style="width: 100%" stripe>
                        <el-table-column label="序号" width="80px" #default="scope" align="center">
                            {{ scope.$index + 1 }}
                        </el-table-column>
                        <el-table-column prop="productName" label="产品名称" width="180" align="center" />
                        <el-table-column prop="productCode" label="产品编码" width="180" align="center" />
                        <el-table-column prop="quantity" label="数量" width="120" align="center" />
                        <el-table-column prop="unitPrice" label="单价" width="120" align="center" />
                        <el-table-column prop="amount" label="金额" width="120" align="center" />
                    </el-table>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDetailDialogClose" size="default">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// Add getPurchasePage to the import statement
import {getPurchaseWithDetails, createPurchase, updatePurchase, deletePurchase, getPurchasePage,getSupplier } from '@/api/purchase/purchase_order';
import { getProductList } from '@/api/warehouse/warehouse';

// 获取组件实例用于表单验证
const { proxy } = getCurrentInstance();

// 采购订单列表数据
const purchaseList = ref([]);

// 添加供应商列表数据
const suppliers = ref([]);

// 产品列表数据
const productList = ref([]);

// 搜索参数
const searchParams = ref({
    orderNo: '',
    supplierName: '',
    startDate: '',
    endDate: ''
});

// 分页参数
const pagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
});

// 对话框状态
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);

// 当前操作的采购订单
const purchaseOrder = ref({});
const currentPurchaseOrder = ref(null);

// 统一解包工具：兼容拦截器返回 data 或原始对象
function unwrap(res) {
    return (res && res.data !== undefined) ? res.data : res;
}

// 统一分页数据解包：兼容 {records,total} 或数组直接返回
function unwrapPageRecords(payload) {
    const data = unwrap(payload);
    if (data && Array.isArray(data.records)) {
        return { records: data.records, total: Number(data.total) || data.records.length };
    }
    if (Array.isArray(data)) {
        return { records: data, total: data.length };
    }
    return { records: [], total: 0 };
}

// 表单验证规则
const formRules = ref({
    supplierId: [
        { required: true, message: '请选择供应商', trigger: 'blur' }
    ],
    orderDate: [
        { required: true, message: '请选择订单日期', trigger: 'change' }
    ]
});

// 获取采购订单列表
// 修改getPurchaseList方法
function getPurchaseList() {
    // 构建分页参数
    const pageParams = {
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize,
        orderNo: searchParams.value.orderNo,
        supplierName: searchParams.value.supplierName,
        startDate: searchParams.value.startDate,
        endDate: searchParams.value.endDate
    };

    getPurchasePage(pageParams).then(res => {
        const page = unwrapPageRecords(res);
        purchaseList.value = page.records;
        pagination.value.total = page.total;
    }).catch(error => {
        ElMessage.error('获取采购订单列表失败');
        console.error('获取采购订单列表失败:', error);
    });
}

// 获取供应商列表
// 在fetchSuppliers函数中添加更详细的错误日志
function fetchSuppliers() {
    getSupplier().then(res => {
        const data = unwrap(res);
        const list = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : []);
        suppliers.value = list;
        console.log('供应商数据:', list);
    }).catch(error => {
        ElMessage.error('获取供应商列表失败');
        console.error('获取供应商列表失败:', error);
        console.error('错误详情:', error.response); // 添加详细错误信息
    });
}

// 重置搜索参数
function resetSearchParams() {
    searchParams.value = {
        orderNo: '',
        supplierName: '',
        startDate: '',
        endDate: ''
    };
    getPurchaseList();
}

// 分页处理
const handleSizeChange = (val) => {
    pagination.value.pageSize = val;
    getPurchaseList();
}
const handleCurrentChange = (val) => {
    pagination.value.pageNum = val;
    getPurchaseList();
}

// 显示创建对话框
function showAddDialog() {
    isEdit.value = false;
    purchaseOrder.value = {};
    dialogVisible.value = true;
    // 重置表单
    proxy.$refs.purchaseForm.resetFields();
    // 重置明细
    purchaseOrder.value.items = [];
}

// 显示编辑对话框
function showEditDialog(row) {
    isEdit.value = true;
    // 获取完整的订单信息（包含明细）
    getPurchaseWithDetails(row.id).then(res => {
        const data = unwrap(res);
        purchaseOrder.value = data || {};
        // 确保明细数组存在
        if (!purchaseOrder.value.items) {
            purchaseOrder.value.items = [];
        }
        // 为每个明细项确保有正确的产品信息
        if (purchaseOrder.value.items && Array.isArray(purchaseOrder.value.items)) {
            purchaseOrder.value.items.forEach(item => {
                // 如果明细中没有productName，从产品列表中获取
                if (item.productId && !item.productName) {
                    const product = productList.value.find(p => p.id === item.productId);
                    if (product) {
                        item.productName = product.name;
                        item.productCode = product.barcode || product.code;
                    }
                }
                // 确保金额计算正确
                if (item.quantity && item.unitPrice) {
                    item.amount = (Number(item.quantity) || 0) * (Number(item.unitPrice) || 0);
                }
            });
        }
        dialogVisible.value = true;
    }).catch(error => {
        ElMessage.error('获取采购订单详情失败');
        console.error('获取订单详情失败:', error);
        // 如果获取详情失败，使用基本信息
        purchaseOrder.value = { ...row, items: [] };
        dialogVisible.value = true;
    });
}

// 关闭对话框
function handleDialogClose() {
    dialogVisible.value = false;
    // 重置表单
    proxy.$refs.purchaseForm.resetFields();
    // 重置明细
    purchaseOrder.value.items = [];
}

// 明细操作方法
function addItem() {
    if (!purchaseOrder.value.items) purchaseOrder.value.items = [];
    purchaseOrder.value.items.push({ productId: '', quantity: 1, unitPrice: 0, amount: 0 });
}
function removeItem(index) {
    purchaseOrder.value.items.splice(index, 1);
}
function handleProductChange(row, val) {
    // 自动带出产品名/编码等
    const prod = productList.value.find(p => p.id === val);
    if (prod) {
        row.productName = prod.name;
        row.productCode = prod.barcode || prod.code;
        // 如果产品有默认价格，可以自动填入
        if (prod.price && !row.unitPrice) {
            row.unitPrice = prod.price;
            calcAmount(row);
        }
    }
}
function calcAmount(row) {
    row.amount = (Number(row.quantity) || 0) * (Number(row.unitPrice) || 0);
}

// 提交表单时带上明细
function submitForm() {
    proxy.$refs.purchaseForm.validate((valid) => {
        if (valid) {
            // 明细校验
            if (!purchaseOrder.value.items || purchaseOrder.value.items.length === 0) {
                ElMessage.warning('请添加至少一条商品明细');
                return;
            }
            for (const item of purchaseOrder.value.items) {
                if (!item.productId || !item.quantity || !item.unitPrice) {
                    ElMessage.warning('请完善所有商品明细');
                    return;
                }
            }
            if (isEdit.value) {
                updatePurchase(purchaseOrder.value).then(res => {
                    ElMessage.success('采购订单更新成功');
                    handleDialogClose();
                    getPurchaseList();
                }).catch(error => {
                    ElMessage.error('采购订单更新失败');
                    console.error('更新失败:', error);
                });
            } else {
                purchaseOrder.value.status = 0;
                purchaseOrder.value.createUser = Number(localStorage.getItem("userId")) || 1;
                purchaseOrder.value.tenantId = Number(localStorage.getItem("tenantId")) || 1;
                createPurchase(purchaseOrder.value).then(res => {
                    ElMessage.success('采购订单创建成功');
                    handleDialogClose();
                    getPurchaseList();
                }).catch(error => {
                    ElMessage.error('采购订单创建失败');
                    console.error('创建失败:', error);
                });
            }
        } else {
            ElMessage.warning('请完善采购订单信息并确保格式正确');
            return false;
        }
    });
}

// 查看采购订单详情
function viewPurchaseDetails(id) {
    getPurchaseWithDetails(id).then(res => {
        const data = unwrap(res);
        currentPurchaseOrder.value = data || null;
        detailDialogVisible.value = true;
    }).catch(error => {
        ElMessage.error('获取采购订单详情失败');
        console.error('获取详情失败:', error);
    });
}

// 关闭详情对话框
function handleDetailDialogClose() {
    detailDialogVisible.value = false;
    currentPurchaseOrder.value = null;
}

// 删除采购订单
function deletePurchaseOrder(id) {
    ElMessageBox.confirm(
        '确定要删除该采购订单吗？此操作不可撤销。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        deletePurchase(id).then(res => {
            ElMessage.success('采购订单删除成功');
            getPurchaseList();
        }).catch(error => {
            ElMessage.error('采购订单删除失败');
            console.error('删除失败:', error);
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

// 页面加载时获取采购订单列表和供应商列表
onMounted(() => {
    getPurchaseList();
    fetchSuppliers();
    getProductList().then(res => {
        const data = unwrap(res);
        productList.value = Array.isArray(data) ? data : [];
    });
});
</script>

<style scoped>
.purchase-order-container {
    padding: 20px;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.purchase-detail {
    padding: 10px;
}

.detail-header {
    margin-bottom: 20px;
}

.detail-header p {
    margin: 8px 0;
}

.label {
    font-weight: bold;
    display: inline-block;
    width: 100px;
}

.detail-items h3 {
    margin-bottom: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>
